<template>
  <div class="users-page">
    <el-card>
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <span>用户管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            添加用户
          </el-button>
        </div>
      </template>
      
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :model="searchForm" inline>
          <el-form-item label="用户名">
            <el-input
              v-model="searchForm.username"
              placeholder="请输入用户名"
              clearable
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="启用" value="1" />
              <el-option label="禁用" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="角色">
            <el-select v-model="searchForm.roleId" placeholder="请选择角色" clearable>
              <el-option 
                v-for="role in availableRoles" 
                :key="role.id" 
                :label="role.name" 
                :value="role.id" 
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 用户表格 -->
      <el-table :data="tableData" :loading="loading" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="role" label="角色" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <TableActionDropdown
              :actions="getActionList(row)"
              :row="row"
              @action="handleAction"
            />
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div style="margin-top: 20px; text-align: right;">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Delete, Lock, Unlock } from '@element-plus/icons-vue'
import TableActionDropdown from '@/components/TableActionDropdown.vue'
import { userAPI } from '@/api/user'
import { roleAPI } from '@/api/role'

const searchForm = reactive({
  username: '',
  status: '',
  roleId: ''
})

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const availableRoles = ref([])

const handleAdd = () => {
  ElMessage.info('添加用户功能')
}

const handleEdit = (row) => {
  ElMessage.info(`编辑用户: ${row.username}`)
}

const handleToggleStatus = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.status === 'active' ? '禁用' : '启用'}用户 ${row.username} 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    row.status = row.status === 'active' ? 'inactive' : 'active'
    ElMessage.success('操作成功')
  } catch {
    // 用户取消
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 ${row.username} 吗？此操作不可恢复！`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
    
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  } catch {
    // 用户取消
  }
}

// 加载表格数据
const loadTableData = async () => {
  loading.value = true
  try {
    const response = await userAPI.getUsers({
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      keyword: searchForm.username,
      status: searchForm.status,
      roleId: searchForm.roleId
    })
    
    if (response.success) {
      // 获取用户数据
      const users = response.data.records || []
      pagination.total = response.data.total || 0
      
      // 为每个用户获取详细信息（包含角色和分组）
      const usersWithDetails = await Promise.all(users.map(async (user) => {
        try {
          const userResponse = await userAPI.getUserById(user.id)
          if (userResponse.success) {
            // 从UserVO中提取用户、角色和分组信息
            const userVO = userResponse.data || {}
            const roles = userVO.roles || []
            
            // 提取角色名称
            const roleNames = roles.map(role => role.name || '未知角色').join(', ')
            
            return { 
              ...user, 
              role: roleNames || '无角色',
              status: user.status === 1 ? 'active' : 'inactive'
            }
          } else {
            console.warn(`获取用户 ${user.id} 的详细信息失败:`, userResponse.message)
            return { 
              ...user, 
              role: '无角色',
              status: user.status === 1 ? 'active' : 'inactive'
            }
          }
        } catch (error) {
          console.error(`获取用户 ${user.id} 的详细信息时出错:`, error)
          return { 
            ...user, 
            role: '无角色',
            status: user.status === 1 ? 'active' : 'inactive'
          }
        }
      }))
      
      tableData.value = usersWithDetails
      ElMessage.success('数据加载成功')
    } else {
      ElMessage.error(response.message || '加载数据失败')
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 加载角色数据
const loadRoles = async () => {
  try {
    const roleResponse = await roleAPI.getRoles({ pageNum: 1, pageSize: 1000 })
    if (roleResponse.success) {
      availableRoles.value = roleResponse.data.records || []
    }
  } catch (error) {
    console.error('加载角色数据失败:', error)
  }
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadTableData()
}

const handleReset = () => {
  searchForm.username = ''
  searchForm.status = ''
  searchForm.roleId = ''
  pagination.currentPage = 1
  loadTableData()
}

const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  loadTableData()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  loadTableData()
}

// 获取操作列表
const getActionList = (row) => {
  return [
    {
      command: 'edit',
      label: '编辑',
      icon: Edit,
      type: 'info'
    },
    {
      command: 'toggle-status',
      label: row.status === 'active' ? '禁用' : '启用',
      icon: row.status === 'active' ? Lock : Unlock,
      type: row.status === 'active' ? 'warning' : 'success'
    },
    {
      command: 'delete',
      label: '删除',
      icon: Delete,
      type: 'danger',
      divided: true
    }
  ]
}

// 处理操作事件
const handleAction = ({ command, row }) => {
  switch (command) {
    case 'edit':
      handleEdit(row)
      break
    case 'toggle-status':
      handleToggleStatus(row)
      break
    case 'delete':
      handleDelete(row)
      break
    default:
      console.warn('未知操作:', command)
  }
}

onMounted(() => {
  loadRoles()
  loadTableData()
})
</script>

<style scoped>
.users-page {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}
</style>